package com.jungle.task;

import com.jungle.exception.FscException;
import com.jungle.task.parameter.TaskParameter;
import com.jungle.task.result.TaskResult;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * @author 李岩 at 2021/10/22.
 */
@Slf4j
public class TaskPool<T extends TaskParameter,V extends TaskResult> {
    private final BlockingQueue<Task<T,V>> taskQueue;

    public TaskPool(){
        this.taskQueue = new ArrayBlockingQueue<>(100);
    }

    public void publishTask(final Task<T,V> task){
        this.taskQueue.add(task);
    }

    public Task<T,V> takeTask(){
        try {
            return taskQueue.take();
        } catch (final InterruptedException e) {
            throw new FscException("fsc任务池，获取任务异常",e);
        }
    }

    public Task<T,V> takeTask(final long timeout){
        return takeTask(timeout,TimeUnit.MILLISECONDS);
    }

    public Task<T,V> takeTask(final long timeout, final TimeUnit unit){
        try {
            return taskQueue.poll(timeout, unit);
        } catch (final InterruptedException e) {
            throw new FscException("fsc任务池，获取任务异常",e);
        }
    }
}
